﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Text;
using System.Linq;

namespace Tools.Utils
{
    public class ImageHelper
    {
        /// <summary>
        /// 等比例缩放图片
        /// </summary>
        /// <param name="bitmap"></param>
        /// <param name="destHeight"></param>
        /// <param name="destWidth"></param>
        /// <returns></returns>
        public Bitmap ZoomImage(Bitmap bitmap, int destHeight1, int destWidth1)
        {
            try
            {
                //获取图片宽度
                int sourceWidth = bitmap.Width;
                //获取图片高度
                int sourceHeight = bitmap.Height;

                float nPercent = 0;
                float nPercentW = 0;
                float nPercentH = 0;
                //计算宽度的缩放比例
                nPercentW = ((float)destWidth1 / (float)sourceWidth);
                //计算高度的缩放比例
                nPercentH = ((float)destHeight1 / (float)sourceHeight);

                if (nPercentH < nPercentW)
                    nPercent = nPercentH;
                else
                    nPercent = nPercentW;
                //期望的宽度
                int destWidth = (int)(sourceWidth * nPercent);
                //期望的高度
                int destHeight = (int)(sourceHeight * nPercent);

                Bitmap b = new Bitmap(destWidth, destHeight);
                Graphics g = Graphics.FromImage((System.Drawing.Image)b);
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                //绘制图像
                g.DrawImage(bitmap, 0, 0, destWidth, destHeight);
                g.Dispose();
                return b;
                //Image sourImage = bitmap;
                ////ImageCodecInfo ici = GetEncoder(ImageFormat.Jpeg);
                //int width = 0, height = 0;
                ////按比例缩放           
                //int sourWidth = sourImage.Width;
                //int sourHeight = sourImage.Height;
                //if (sourHeight > destHeight || sourWidth > destWidth)
                //{
                //    if ((sourWidth * destHeight) > (sourHeight * destWidth))
                //    {
                //        width = destWidth;
                //        height = (destWidth * sourHeight) / sourWidth;
                //    }
                //    else
                //    {
                //        height = destHeight;
                //        width = (sourWidth * destHeight) / sourHeight;
                //    }
                //}
                //else
                //{
                //    width = sourWidth;
                //    height = sourHeight;
                //}
                //Bitmap destBitmap = new Bitmap(destWidth, destHeight);
                //Graphics g = Graphics.FromImage(destBitmap);
                //g.Clear(Color.Transparent);
                ////设置画布的描绘质量         
                //g.CompositingQuality = CompositingQuality.HighQuality;
                //g.SmoothingMode = SmoothingMode.HighQuality;
                //g.InterpolationMode = InterpolationMode.HighQualityBilinear;
                //g.DrawImage(sourImage, new Rectangle((destWidth - width) / 2, (destHeight - height) / 2, width, height), 0, 0, sourImage.Width, sourImage.Height, GraphicsUnit.Pixel);
                //g.Dispose();
                ////设置压缩质量     
                //EncoderParameters encoderParams = new EncoderParameters();
                //long[] quality = new long[1];
                //quality[0] = 100;
                //EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
                //encoderParams.Param[0] = encoderParam;
                //sourImage.Dispose();
                //return destBitmap;
            }
            catch
            {
                return bitmap;
            }
        }

        /// <summary>
        /// 将图片转为32位的位图
        /// </summary>
        /// <param name="img"></param>
        /// <returns></returns>
        public Bitmap ConvertTo32bpp(Image img)
        {
            var bmp = new Bitmap(img.Width, img.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
            using (var gr = Graphics.FromImage(bmp))
                gr.DrawImage(img, new Rectangle(0, 0, img.Width, img.Height));
            return bmp;
        }

        /// <summary>
        /// 图片背景透明化 
        /// </summary>
        /// <param name="img"></param>
        /// <param name="w"></param>
        /// <param name="h"></param>
        /// <returns></returns>
        public Bitmap Conver_1(Bitmap img, int w, int h)
        {
            Bitmap bt = new Bitmap(ConvertTo32bpp(img));
            Rectangle rect = new Rectangle(0, 0, bt.Width, bt.Height);
            BitmapData bmpdata = bt.LockBits(rect, ImageLockMode.ReadWrite, bt.PixelFormat);
            IntPtr ptr = bmpdata.Scan0;
            int bytes = Math.Abs(bmpdata.Stride) * bt.Height;
            byte[] rgbValues = new byte[bytes];
            System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
            int len = rgbValues.Length;
            byte a = (byte)40;//颜色的误差范围
            for (int i = 0; i < len; i += 4)
            {
                //Format32bppRgb是用4个字节表示一个像素,第一个字节表示RGB的B值,第一个表示为G值,第三个表示为R值,第四个表示为Alpha值
                if (Math.Abs(rgbValues[i] - rgbValues[0]) < a && Math.Abs(rgbValues[i + 1] - rgbValues[1]) < a && Math.Abs(rgbValues[i + 2] - rgbValues[2]) < a)
                {
                    rgbValues[i + 3] = (byte)0;
                }
            }
            System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes);
            bt.UnlockBits(bmpdata);
            return bt;
        }

        /// <summary>
        /// 指定颜色替换成另一种颜色
        /// </summary>
        /// <param name="img">原图</param>
        /// <param name="w">图宽</param>
        /// <param name="h">图高</param>
        /// <param name="R">要被替换颜色的RGB的R</param>
        /// <param name="G">要被替换颜色的RGB的G</param>
        /// <param name="B">要被替换颜色的RGB的B</param>
        /// <param name="r">替换色的RGB的R</param>
        /// <param name="g">替换色的RGB的G</param>
        /// <param name="b">替换色的RGB的B</param>
        /// <returns>处理后的结果图像   </returns>
        public void Conver_3(Bitmap map, int r, int g, int b, string savePath)
        {
            
            //////通过左上角一个点获取图片的背景色
            //var color = map.GetPixel(1, 1);
            //var R = color.R;
            //var G = color.G;
            //var B = color.B;

            //Bitmap bt = new Bitmap(ConvertTo32bpp(map));
            //Rectangle rect = new Rectangle(0, 0, map.Width, map.Height);
            //BitmapData bmpdata = bt.LockBits(rect, ImageLockMode.ReadWrite, bt.PixelFormat);
            //IntPtr ptr = bmpdata.Scan0;
            //int bytes = Math.Abs(bmpdata.Stride) * bt.Height;
            //byte[] rgbValues = new byte[bytes];
            //System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
            //int len = rgbValues.Length;
            //byte a = 125;
            //byte R1 = (byte)R;
            //byte G1 = (byte)G;
            //byte B1 = (byte)B;
            //byte r1 = (byte)r;
            //byte g1 = (byte)g;
            //byte b1 = (byte)b;
            //for (int i = 0; i < len; i += 4)
            //{
            //    //Format32bppRgb是用4个字节表示一个像素,第一个字节表示RGB的B值,第二个表示为G值,第三个表示为R值,第四个表示为Alpha值
            //    if (Math.Abs(rgbValues[i] - B1) < a && Math.Abs(rgbValues[i + 1] - G1) < a && Math.Abs(rgbValues[i + 2] - R1) < a)
            //    {
            //        rgbValues[i] = b1;
            //        rgbValues[i + 1] = g1;
            //        rgbValues[i + 2] = r1;
            //    }
            //}
            //System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes);
            //bt.UnlockBits(bmpdata);

            //bt.Save(savePath);
            //var dad = "";
            //return bt;
            int upnum = 100;
            int downnum = 0;
            double trackvalue = 90;
            List<int> colorrgb = getmodecolor(map);
            //上半部分去除颜色范围
            List<int> upcolorrgb = new List<int>();
            //下半部分去除颜色范围
            List<int> downcolorrgb = new List<int>();
            for (int i = 0; i < colorrgb.Count(); i++)
            {
                if (i > 2)
                {
                    upcolorrgb.Add(colorrgb[i] - upnum < 0 ? 0 : colorrgb[i] - upnum);
                    downcolorrgb.Add(colorrgb[i] - downnum < 0 ? 0 : colorrgb[i] - downnum);
                }
                else
                {
                    upcolorrgb.Add(colorrgb[i] + upnum > 255 ? 255 : colorrgb[i] + upnum);
                    downcolorrgb.Add(colorrgb[i] + downnum > 255 ? 255 : colorrgb[i] + downnum);
                }
            }
            //从左到右，从上到下读取像素点

            using (Bitmap editmap = new Bitmap(map, map.Width, map.Height))
            {
                // 上半部分
                for (int i = 0; i < map.Width; i++)
                {
                    for (int j = 0; j < (int)(map.Height * (trackvalue / 100)); j++)
                    {
                        Color color = editmap.GetPixel(i, j);
                        //判断像素是否可以移除
                        if (color.R >= upcolorrgb[3] && color.R <= upcolorrgb[0] &&
                         color.G >= upcolorrgb[4] && color.G <= upcolorrgb[1] &&
                         color.B >= upcolorrgb[5] && color.B <= upcolorrgb[2])
                        {
                            editmap.SetPixel(i, j, Color.FromArgb(r,g,b));
                        }
                    }
                }
                //下半部分
                for (int i = 0; i < map.Width; i++)
                {
                    for (int j = (int)(map.Height * (trackvalue / 100)); j < map.Height; j++)
                    {
                        //判断像素是否可以移除
                        Color color = editmap.GetPixel(i, j);
                        if (color.R >= downcolorrgb[3] && color.R <= downcolorrgb[0] &&
                         color.G >= downcolorrgb[4] && color.G <= downcolorrgb[1] &&
                         color.B >= downcolorrgb[5] && color.B <= downcolorrgb[2])

                        {
                            editmap.SetPixel(i, j, Color.FromArgb(r, g, b));

                        }
                    }
                }
                editmap.Save(savePath);

            }

        }

        /// <summary>
        /// 指定颜色透明化
        /// </summary>
        /// <param name="img">原图</param>
        /// <param name="w">原图宽度</param>
        /// <param name="h">原图高度</param>
        /// <param name="R">指定颜色RGB的R值</param>
        /// <param name="G">指定颜色RGB的G值</param>
        /// <param name="B">指定颜色RGB的B值</param>
        /// <returns>处理后的结果图像</returns>
        public Bitmap Conver_2(Bitmap img, int w, int h, int R, int G, int B)
        {

            //测试结果不成功,图片没有变化
            Bitmap bt = new Bitmap(ConvertTo32bpp(img));
            Rectangle rect = new Rectangle(0, 0, w, h);
            BitmapData bmpdata = bt.LockBits(rect, ImageLockMode.ReadWrite, bt.PixelFormat);
            IntPtr ptr = bmpdata.Scan0;
            int bytes = Math.Abs(bmpdata.Stride) * bt.Height;
            byte[] rgbValues = new byte[bytes];
            System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
            int len = rgbValues.Length;
            byte a = 40;
            byte R1 = (byte)R;
            byte G1 = (byte)G;
            byte B1 = (byte)B;
            for (int i = 0; i < len; i += 4)
            {
                //Format32bppRgb是用4个字节表示一个像素,第一个字节表示RGB的B值,第一个表示为G值,第三个表示为R值,第四个表示为Alpha值
                if (Math.Abs(rgbValues[i] - B1) < a && Math.Abs(rgbValues[i + 1] - G1) < a && Math.Abs(rgbValues[i + 2] - R1) < a)
                {
                    rgbValues[i + 3] = (byte)0;
                }
            }
            System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes);
            bt.UnlockBits(bmpdata);
            return bt;
        }



        /// <summary>
        /// 获取前五排像素，求出rgb范围
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private List<int> getmodecolor( Bitmap map)
        {
            List<int> colorrgb = new List<int>();
            List<int> rlist = new List<int>();
            List<int> glist = new List<int>();
            List<int> blist = new List<int>();
            //using (Bitmap map = (Bitmap)Image.fromfile(path))
            //{
            using (Bitmap editmap = new Bitmap(map, map.Width, map.Height))
            {
                // editmap.getpixel()
                for (int i = 0; i < map.Width; i++)
                {
                    for (int j = 0; j < 3; j++)
                    {
                        Color color = editmap.GetPixel(i, j);
                        if (!rlist.Contains(color.R))
                        {
                            rlist.Add(color.R);
                        }
                        if (!glist.Contains(color.G))
                        {
                            glist.Add(color.G);
                        }
                        if (!blist.Contains(color.B))
                        {
                            blist.Add(color.B);
                        }
                    }
                }
                //添加rgb像素范围
                colorrgb.Add(rlist.Max());
                colorrgb.Add(glist.Max());
                colorrgb.Add(blist.Max());
                colorrgb.Add(rlist.Min());
                colorrgb.Add(glist.Min());
                colorrgb.Add(blist.Min());
            }
            //}
            return colorrgb;
        }

    }
}
